#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
支付宝账单解析模块
"""

import pandas as pd
import chardet
from typing import List, Dict
from datetime import datetime
import re
import warnings
warnings.filterwarnings('ignore')

from wechat_parser import Transaction


def parse_alipay_bill(file_path: str) -> List[Transaction]:
    """解析支付宝账单文件"""
    try:
        # 读取Excel文件
        df = pd.read_excel(file_path, header=None)
        
        # 找到实际数据的起始行（包含列名的行）
        header_row_index = None
        for i in range(min(20, len(df))):  # 在前20行中查找
            row = df.iloc[i]
            if '交易时间' in str(row.tolist()) and ('收/支' in str(row.tolist()) or '收入/支出' in str(row.tolist())):
                header_row_index = i
                break
        
        if header_row_index is None:
            raise ValueError("无法找到支付宝账单的列名行")
        
        # 重新读取数据，设置正确的列名
        df_data = pd.read_excel(file_path, header=header_row_index)
        
        # 删除完全为空的行
        df_data = df_data.dropna(how='all')
        
        # 清理列名
        df_data.columns = [str(col).strip() for col in df_data.columns]
        
        transactions = []
        
        # 遍历每一行数据
        for _, row in df_data.iterrows():
            try:
                # 解析交易时间
                timestamp = row.get('交易时间', '')
                if pd.isna(timestamp):
                    continue
                
                # 转换时间格式
                if isinstance(timestamp, str):
                    # 尝试不同的日期格式
                    for fmt in ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d']:
                        try:
                            dt = datetime.strptime(timestamp, fmt)
                            timestamp = dt.strftime('%Y-%m-%d %H:%M:%S')
                            break
                        except ValueError:
                            continue
                    else:
                        # 如果所有格式都失败，保持原样
                        pass
                else:
                    # 假设是datetime对象
                    timestamp = timestamp.strftime('%Y-%m-%d %H:%M:%S')
                
                # 解析交易类型和金额
                type_indicator = str(row.get('收/支', row.get('收入/支出', '')))
                amount_str = str(row.get('金额(元)', row.get('金额', '')))
                
                # 清理金额字符串
                amount_str = re.sub(r'[￥,\s]', '', amount_str)
                amount = float(amount_str) if amount_str else 0.0
                
                # 确定交易类型
                trans_type = '支出'
                if '收入' in type_indicator or '/' not in type_indicator:
                    trans_type = '收入'
                elif '支出' in type_indicator:
                    trans_type = '支出'
                
                # 如果是支出，金额应为负数
                if trans_type == '支出' and amount > 0:
                    amount = -amount
                
                # 获取交易分类
                category = str(row.get('交易分类', row.get('分类', '')))
                if not category or category == 'nan':
                    category = '其他'
                
                # 处理二级分类
                subcategory = ''
                if '商品分类' in row:
                    subcategory = str(row.get('商品分类', ''))
                
                # 构造分类字符串，格式为"一级分类|二级分类"
                if subcategory and subcategory != 'nan':
                    category = f"{category}|{subcategory}"
                
                # 获取交易对方
                payee = str(row.get('交易对方', row.get('对方', '')))
                if not payee or payee == 'nan':
                    payee = ''
                
                # 获取商品说明
                note = str(row.get('商品说明', row.get('说明', '')))
                if not note or note == 'nan':
                    note = ''
                
                # 获取支付方式
                source = str(row.get('支付方式', row.get('付款方式', '')))
                if not source or source == 'nan':
                    source = '支付宝'
                
                # 创建交易对象
                transaction = Transaction(
                    timestamp=timestamp,
                    amount=amount,
                    type=trans_type,
                    category=category,
                    payee=payee,
                    source=source,
                    note=note
                )
                
                transactions.append(transaction)
                
            except Exception as e:
                # 跳过解析失败的行
                print(f"解析支付宝账单行时出错: {str(e)}")
                continue
        
        return transactions
        
    except Exception as e:
        raise Exception(f"解析支付宝账单文件时出错: {str(e)}")